<template>
    <div>
        <div v-if="!(chatList.length > 0) && condition === true" class="welcome-container">
            <div class="welcome-header">
                <img class="welcome-image" :src="Union" alt="">
                <span class="welcome-text">我是AI物料助手，很高兴见到你！</span>
            </div>
            <div class="welcome-subtext">我可以回答你物料的一些问题，请把向我提问吧~</div>
        </div>
        <div v-if="!(chatList.length > 0) && condition === false" class="topcontent">
            <div class="topImg"><img src="@/assets/images/humanBrain.png" alt=""></div>
            <div class="topTitle">
                <div class="title-main">欢迎使用</div>
                <div class="title-sub">在这里，您可以和小助手沟通问答。</div>
            </div>
        </div>
        <t-chat layout="both" reverse="true"
            :style="chatList.length > 0 ? { height: '84vh', width: '100%' } : { height: '64vh', width: '100%' }"
            :data="chatList" :clear-history="chatList.length > 0 && !isStreamLoad" :text-loading="loading"
            :is-stream-load="isStreamLoad" @on-action="operation" @clear="clearConfirm">
            <!-- eslint-disable-next-line vue/no-unused-vars -->
            <template #content="{ item }">
                <div class="MarkdownContent" v-if="item.content">
                    <MarkdownContent :content="item.content" />
                </div>

                <div class="content-spacer"></div>

                <div v-if="item.hasTable && item.tableData">
                    <DynamicTable :data="item.tableData" />
                </div>
            </template>
            <template #actions="{ item, index }">
                <t-chat-action :content="item.content" :operation-btn="['replay', 'copy']"
                    @operation="(type) => handleOperation(type, item, index)" />
            </template>
            <template #footer>
                <t-chat-sender v-model="localChatValue" :textarea-props="{
                    placeholder: '请输入你需要的内容',
                }" :loading="loading" :stop-disabled="isStreamLoad" @send="inputEnter" @stop="onStop">

                    <template #suffix="{ renderPresets }">
                        <component v-if="isStreamLoad" style="display: none" :is="renderPresets([])" />
                        <xcmg-button v-if="!isStreamLoad" type="primary" theme="default" variant="text"
                            @click="handleSendClick">
                            <img style="margin-bottom: 4px;" src="@/assets/images/star.png" alt="">
                            <div class="button-spacer"></div>
                            发送
                        </xcmg-button>
                    </template>
                </t-chat-sender>
            </template>
        </t-chat>
    </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { streamPost, getTableData } from '@/util/http'
import { XcmgMessage } from 'xcmg-components'
import Union from '@/assets/images/Union.png'
import MarkdownContent from '@/components/MarkdownContent.vue'
import DynamicTable from '@/components/DynamicTable.vue';

const props = defineProps({
    chatValue: String,
    condition: {
        type: Boolean,
        default: false
    }
});
const localChatValue = ref(props.chatValue || '');

watch(() => props.chatValue, (newVal) => {
    localChatValue.value = `我想问${newVal}` || '';
});

const loading = ref(false);
const isStreamLoad = ref(false);
const currentAssistantIndex = ref(-1);
const eventSourceRef = ref<EventSource | null>(null);
const abortControllerRef = ref<AbortController | null>(null);

const formatTime = (date: Date) => {
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const inputDate = new Date(date);

    const timeStr = inputDate.toTimeString().substring(0, 5);

    if (inputDate >= today) {
        return `今天 ${timeStr}`;
    } else if (inputDate >= new Date(today.setDate(today.getDate() - 1))) {
        return `昨天 ${timeStr}`;
    } else {
        return `${inputDate.getMonth() + 1}/${inputDate.getDate()}`;
    }
};

const chatList = ref([
    {
        avatar: Union,
        content: `你好！很高兴为您服务。请告诉我您需要什么样的设备，比如发动机或电动车，以及您的一些具体需求或参数，我会尽力为您推荐合适的产品。`,
        hasTable: true,
        tableData: [
            { "任务ID": "TASK-101", "负责人": "赵明", "进度": "100%" },
            { "任务ID": "TASK-102", "负责人": "钱小琳", "进度": "75%" }
        ],
        role: 'assistant',
    },
    {
        content: '你好',
        role: 'user',
    },
]);

// 复制到剪贴板函数
const copyToClipboard = async (text: string) => {
    fallbackCopyToClipboard(text);
};

// 降级复制方案
const fallbackCopyToClipboard = (text: string) => {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.top = '0';
    textArea.style.left = '0';
    textArea.style.position = 'fixed';
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();

    try {
        const successful = document.execCommand('copy');
        if (successful) {
            XcmgMessage({
                message: '已成功复制到剪贴板',
                type: 'success',
                plain: true,
                showClose: true
            })
        }
    } catch (err) {
        console.error('降级复制也失败了: ', err);
    }

    document.body.removeChild(textArea);
};

// 将表格数据格式化为文本
const formatTableForCopy = function (tableData: any[]): string {
    if (!tableData || tableData.length === 0) return '';

    const columns = Object.keys(tableData[0]);
    let result = columns.join('\t') + '\n';

    tableData.forEach(row => {
        const rowData = columns.map(col => row[col] || '');
        result += rowData.join('\t') + '\n';
    });

    return result;
};

// 处理操作
const handleOperation = function (type: string, item: any, index: number) {
    console.log('handleOperation', type, item, index);

    if (type === 'replay') {
        regenerateResponse(index);
    } else if (type === 'copy') {
        handleCopy(item);
    }
};

// 处理复制
const handleCopy = function (item: any) {
    let contentToCopy = item.content || '';

    // if (item.hasTable && item.tableData && item.tableData.length > 0) {
    //     contentToCopy += '\n\n' + formatTableForCopy(item.tableData);
    // }

    copyToClipboard(contentToCopy);
};

const operation = function (type: string, options: any) {
    console.log(type, options);
};

const clearConfirm = function () {
    chatList.value = [];
};

const onStop = function () {
    if (abortControllerRef.value) {
        abortControllerRef.value.abort();
        abortControllerRef.value = null;
    }
    isStreamLoad.value = false;
    loading.value = false;
};

// 重新生成响应函数
const regenerateResponse = function (index: number) {
    if (isStreamLoad.value) return;

    const userMessageIndex = index + 1;
    if (userMessageIndex >= chatList.value.length || chatList.value[userMessageIndex].role !== 'user') {
        console.error('No user message found for regeneration');
        return;
    }

    const userMessage = chatList.value[userMessageIndex].content;
    const currentTime = new Date();

    chatList.value[index] = {
        ...chatList.value[index],
        content: '',
        hasTable: false,
        tableData: [],
    };

    currentAssistantIndex.value = index;
    startStreamRequest(userMessage);
};

const startStreamRequest = async function (inputValue: string) {
    if (isStreamLoad.value) return;

    // 中断之前的请求
    if (abortControllerRef.value) {
        abortControllerRef.value.abort();
    }

    const controller = new AbortController();
    abortControllerRef.value = controller;

    isStreamLoad.value = true;
    loading.value = true;

    const assistantIndex = currentAssistantIndex.value;
    const sessionId = "abc123";

    try {
        // === 第一步：使用封装的 streamPost 方法进行流式请求 ===
        await streamPost(
            '/stream',
            {
                query: inputValue,
                session_id: sessionId
            },
            controller,
            (chunk) => {
                // 处理数据流
                if (chunk && assistantIndex !== -1 && chatList.value[assistantIndex]) {
                    chatList.value[assistantIndex].content += chunk;
                }
                loading.value = false;
            },
            () => {

                // 流结束后开始请求表格数据
                if (controller.signal.aborted) return;

                getTableData(sessionId)
                    .then((tableData) => {
                        console.log('tableData', tableData)
                        if (Array.isArray(tableData) && tableData.length > 0 &&
                            assistantIndex !== -1 && chatList.value[assistantIndex]) {
                            chatList.value[assistantIndex].hasTable = true;
                            chatList.value[assistantIndex].tableData = tableData;
                        }
                    })
                    .catch((error) => {
                        if (!controller.signal.aborted) {
                            console.error('获取表格数据失败:', error);
                            if (assistantIndex !== -1 && chatList.value[assistantIndex]) {
                                chatList.value[assistantIndex].content += `\n\n[获取表格数据时出错：${error.message}]`;
                            }
                        }
                    });
            },
            (error) => {
                // 错误处理
                if (!controller.signal.aborted) {
                    console.error('流式请求失败:', error);
                    if (assistantIndex !== -1 && chatList.value[assistantIndex]) {
                        chatList.value[assistantIndex].content += `\n\n[获取数据时出错：${error.message}]`;
                    }
                }
            }
        );

    } catch (error: any) {
        if (controller.signal.aborted) {
            console.log('Request was aborted');
        } else {
            console.error('请求失败:', error);
            if (assistantIndex !== -1 && chatList.value[assistantIndex]) {
                chatList.value[assistantIndex].content += `\n\n[获取数据时出错：${error.message}]`;
            }
        }
    } finally {
        // 清理
        if (abortControllerRef.value === controller) {
            abortControllerRef.value = null;
        }
        isStreamLoad.value = false;
        loading.value = false;
        currentAssistantIndex.value = -1;
    }
};


const handleSendClick = function () {
    if (localChatValue.value.trim()) {
        inputEnter(localChatValue.value);
    }
};

// 修改 inputEnter 函数以处理空值
const inputEnter = function (inputValue: string) {
    if (isStreamLoad.value || !inputValue?.trim()) return;

    const currentTime = new Date();
    chatList.value.unshift({
        // avatar: 'https://tdesign.gtimg.com/site/avatar.jpg',
        // name: '自己',
        // datetime: formatTime(currentTime),
        content: inputValue,
        role: 'user',
    });

    chatList.value.unshift({
        avatar: Union,
        // name: '物料规范AI',
        // datetime: formatTime(currentTime),
        content: '',
        hasTable: false,
        tableData: [],
        role: 'assistant',
    });

    currentAssistantIndex.value = 0;
    startStreamRequest(inputValue);
    localChatValue.value = '';
};

const handleStreamError = function (errorMsg: string) {
    if (currentAssistantIndex.value !== -1) {
        chatList.value[currentAssistantIndex.value].content = errorMsg;
        chatList.value[currentAssistantIndex.value].role = 'error';
    }
    if (eventSourceRef.value) {
        eventSourceRef.value.close();
        eventSourceRef.value = null;
    }
    isStreamLoad.value = false;
    loading.value = false;
    currentAssistantIndex.value = -1;
};
</script>

<style scoped lang="less">
:deep(.MarkdownContent p) {
    margin: 0;
}

.welcome-container {
    padding-top: 1rem;
    text-align: center;
}

.welcome-header {
    display: flex;
    font-size: 26px;
    justify-content: center;
}

.welcome-image {
    padding-top: 0;
    padding-right: 0.5rem;
    width: 2.75rem;
}

.welcome-text {
    line-height: 2.75rem;
}

.welcome-subtext {
    padding-top: 1rem;
}

.content-spacer {
    height: 20px;
    background-color: #fff;
}

.button-spacer {
    width: 0.25rem;
}

.MarkdownContent {
    padding: 0.5rem;
    font-size: 16px;
}

/* 原有样式保持不变 */
.topcontent {
    display: flex;
    width: 600px;
    height: 136px;
    background-color: #F5F7FF;
}

.topImg {
    margin: auto 0;
    margin-left: 16px;
    width: 146px;
    height: 104px;

    img {
        width: 146px;
        height: 104px;
    }
}

.topTitle {
    margin: auto 0;
    margin-left: 16px;
}

.title-main {
    font-size: 24px;
    font-weight: 400;
}

.title-sub {
    font-size: 14px;
}

:deep(.assistant .t-chat__detail) {
    border-radius: 4px;
    background-color: #EFF2F6;
}

:deep(.user .t-chat__detail) {
    margin-right: 10px;
    border-radius: 4px;
    background-color: #E5EFFF;
}

:deep(.t-chat--normal .t-chat__detail) {
    max-width: min(calc(100% - 10px), 800px);
}

:deep(.t-chat__inner .t-chat__content--base) {
    margin-left: 10px;
    max-width: min(calc(100% - 50px), 800px);
    padding-top: 0;
}

:deep(.t-chat__avatar) {
    padding-top: 0;
}

:deep(.t-chat__actions-margin) {
    margin-left: 0;
}

:deep(.el-button) {
    padding: 8px 10px !important;
}

::-webkit-scrollbar-thumb {
    background-color: var(--td-scrollbar-color);
}

::-webkit-scrollbar-thumb:horizontal:hover {
    background-color: var(--td-scrollbar-hover-color);
}

::-webkit-scrollbar-track {
    background-color: var(--td-scroll-track-color);
}
</style>